<!DOCTYPE html>
<html>

<head>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>物品借用</title>

	<link rel="shortcut icon" href="favicon.ico">
	<link href="css/bootstrap.min.css-v=3.3.5.css"
		  tppabs="http://www.zi-han.net/theme/hplus/css/bootstrap.min.css?v=3.3.5" rel="stylesheet">
	<link href="css/font-awesome.min.css-v=4.4.0.css"
		  tppabs="http://www.zi-han.net/theme/hplus/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
	<link href="css/plugins/iCheck/custom.css"
		  tppabs="http://www.zi-han.net/theme/hplus/css/plugins/iCheck/custom.css" rel="stylesheet">
	<link href="css/animate.min.css" tppabs="http://www.zi-han.net/theme/hplus/css/animate.min.css"
		  rel="stylesheet">
	<link href="css/style.min.css-v=4.0.0.css" tppabs="http://www.zi-han.net/theme/hplus/css/style.min.css?v=4.0.0"
		  rel="stylesheet">
	<base target="_self">
	<link rel="stylesheet" type="text/css" href="./layui/css/layui.css"/>
	<style type="text/css">
		.zhuti::before {
			background: url('img/lg.jpg') no-repeat fixed center;
			background-size: 300px;
			content: "";
			opacity: 0.2;
			/*透明度设置*/
			width: 80%;
			height: 80%;
			position: absolute;
		}
		/*body{*/
		/*	white-space:pre-line;*/
		/*}*/
		.layui-layer-content{
			white-space:pre-line;
		}
	</style>
</head>

<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
	<div class="row">
		<div class="col-sm-12">
			<div class=" zhuti ibox float-e-margins ">
				<div class="ibox-title">
					<h3 style="font-weight: 600;margin-top: 0;">物品借用</h3>
				</div>

				<div class="ibox-content">
					<form class="layui-form" action="#" onsubmit="return false;">
						<div class="form-horizontal">
							<div class="detailDiv"></div>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>

<script src="js/jquery.min.js-v=2.1.4"
		tppabs="http://www.zi-han.net/theme/hplus/js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js-v=3.3.5"
		tppabs="http://www.zi-han.net/theme/hplus/js/bootstrap.min.js?v=3.3.5"></script>
<script src="js/content.min.js-v=1.0.0"
		tppabs="http://www.zi-han.net/theme/hplus/js/content.min.js?v=1.0.0"></script>
<script src="js/plugins/iCheck/icheck.min.js"
		tppabs="http://www.zi-han.net/theme/hplus/js/plugins/iCheck/icheck.min.js"></script>

<script type="text/javascript" src="../../../tajs.qq.com/stats-sId=9051096"
		tppabs="http://tajs.qq.com/stats?sId=9051096" charset="UTF-8"></script>
<script src="./layui/layui.js" type="text/javascript" charset="utf-8"></script>

<script>
    let thingId = []
    let sizeId = []
    let sizeNum = []
    let people = ''
    let college = ''
    let phone = ''
    let tip = ''
    let startTime = ''
    let endTime = ''


    //新增
    let activity = ''
    let damagedetail = ''
    let isdamage = ''
    let place = ''
    //页面入口函数
    $(document).ready(function () {
        addName('具体信息');
        addDetail();
        show();
        initialize();
        layui.use('form', function () {
            var form = layui.form;
            //公安
            form.on('switch(switchTest1)', function (data) {
                // console.log(data.elem.checked);
                var ll = layui.$("input[name='gongan']").is(':checked');
                // layui.$(test).is(':checked');
                if (data.elem.checked == false && $.trim(ll) == $.trim('true')) {
                    document.getElementById('sunhuai').style.display = 'none';
                } else if (data.elem.checked == true && $.trim(ll) == $.trim('true')) {
                    document.getElementById('sunhuai').style.display = 'block';
                } else if (data.elem.checked == false && $.trim(ll) == $.trim('false')) {
                    document.getElementById('sunhuai').style.display = 'none';
                } else {
                    document.getElementById('sunhuai').style.display = 'none';
                }
                ;
            });
        });
    })

    //发送数据（借东西）
    function send() {
        getMsg()
        console.log(notEmpty())
        if (notEmpty()) {

        } else {
            // console.log(111)
            layer.alert('具体信息不能为空')
            thingId = []
            sizeId = []
            sizeNum = []
            return
        }
        // console.log(people)
        // console.log(college)
        // console.log(phone)
        // console.log(tip)
        // console.log("-----")
        // console.log(new Date(startTime))
        // console.log(new Date(endTime))
        // console.log(thingId)
        // console.log(thingId)
        // console.log(sizeId)
        // console.log(sizeNum)
        // console.log(activity)
        // console.log(place)
        // console.log(damagedetail)
        // console.log(isdamage)
        $.ajax({
            type: "POST",
            url: "/user/borrowThing",
            data: {
                reason: tip,
                applicant: people,
                organizer: college,
                tel: phone,
                startTime: startTime,
                endTime: endTime,
                tid: thingId,
                sid: sizeId,
                num: sizeNum,

                //新增
                //活动名称
                actName: activity,
                //借用地点
                place: place
            },
            success: function (msg) {
                // 申请成功，注意查看申请状态！
                // console.log(123)
                console.log(msg)
                layer.alert(msg)
                thingId = []
                sizeId = []
                sizeNum = []
                if (msg == '申请成功，注意查看申请状态！')
                    $('button').hide();
            },
            fail: function () {
                console.log('失败')
            },
            finally: function () {
                console.log('结束')
            }
        });
    }

    //获取数据
    function getMsg() {
        let list = $('input')
        console.log(list)

        people = $('#sqr').val()
        college = $('#ssxy').val()
        phone = $('#lxdh').val()
        tip = $('#bzxx').val()
        startTime = $('#test1').val()
        endTime = $('#test2').val()
        console.log(startTime)
        console.log(endTime)

        //新增
        activity = $('#hdmc').val()
        place = $('#jydd').val()
        damagedetail = $("#isdamage").val()
        if (damagedetail == "") {
            //没损坏--0
            isdamage = 0;
        } else {
            //损坏--1
            isdamage = 1;
        }


        for (let i = 8; i < list.length; i++) {
            if (list[i].value != "") {
                thingId.push(list[i].attributes[1].value)
                sizeId.push(list[i].attributes[0].value)
                sizeNum.push(list[i].value)
            }
        }

    }

    //页面展示
    function show() {
        $.ajax({
            type: "POST",
            url: "/user/getThingsByType",
            data: {flag: 0},
            success: function (msg) {
                console.log(msg)
                for (let i = 0; i < msg.length; i++) {
                    addName(msg[i].name)
                    let content = '<div class="form-group">'
                    let list = msg[i].list;
                    for (let j = 0; j < list.length; j++) {
                        content += addSize(list[j].size, list[j].renum, msg[i].id, list[j].id)
                    }
                    content = content + '</div>';
                    $('.form-horizontal').append(content);
                }


                addSubmit();
                initialize();
            }
        });
    }

    //添加物品名称
    function addName(name) {
        let nameString = '<div class="ibox-title">\n' +
            '                            <h3 style="font-weight: 600;margin-top: 0;padding-right: 500px;">\n' +
            '                                ' + name + ':</h3>\n' +
            '                        </div>'
        $('.form-horizontal').append(nameString);
    }

    //添加物品的一个规格
    function addSize(size, renum, id_thing, id_size) {
        let item = ' <label class="col-sm-3 control-label">' + size + ':</label>\n' +
            '                            <div class="col-sm-2 row" style="margin-bottom: 14px;">\n' +
            '                                <input data-size=' + id_size + ' data-thing=' + id_thing + ' min="0" max=' + renum + ' type="number" class="form-control">\n' +
            '                            </div>'
        return item;
    }

    //    添加提交按钮
    function addSubmit() {
        let button = '<div class="form-group" style="border-top: 4px solid #E7EAEC;">\n' +
            '                            <div class="col-sm-3 col-sm-offset-4" style="margin-top: 20px;">\n' +
            '                                <button onclick="send()" class="btn btn-primary" type="submit"\n' +
            '                                        style="margin-right: 20%;">提交申请</button>\n' +
            '                                <button class="btn btn-white" type="reset">重新填写</button>\n' +
            '                            </div>\n' +
            '                        </div>'
        $('.form-horizontal').append(button)
    }

    //    添加详细信息
    function addDetail() {
        let detail = '<div class="form-group" style="margin-bottom: 0px;">\' ' +
            '                           <label class="col-sm-2 control-label">活动名称</label>  ' +
            '                      <div class="col-sm-3"> ' +
            '                             <input id="hdmc" type="text" name="" required placeholder="请输入活动名称" class="form-control">' +
            '                             ' +
            '                      </div>' +
            ' <label class="col-sm-2 control-label">活动方(所属学院)</label>' +
            '<div class="col-sm-4">' +
            '  <input id="ssxy" type="text" name="meetingname" required placeholder="请输入所属学院"' +
            '        class="form-control">' +
            '  </div>' +
            ' </div><br>' +
            '                            <label class="col-sm-2 control-label">申请人</label>' +
            '                            <div class="col-sm-3">' +
            '                                <input id="sqr"  type="text" name="" style="margin-left:-8px" required placeholder="请输入申请人"\n' +
            '                                       class="form-control">\n' +
            '                            </div>\n' +
            '<div class="form-group" style="margin-bottom: 0px;">\n' +
            '                            <label class="col-sm-2 control-label">联系电话</label>\n' +
            '                            <!-- col-sm-4 m-l-n -->\n' +
            '                            <div class="col-sm-3">\n' +
            '                                <input id="lxdh" type="text" name="" required placeholder="请输入联系电话"\n' +
            '                                       class="form-control">\n' +
            '                            </div>\n' +
            '                          <label class="col-sm-2 control-label" style="margin-top: 15px">借用地点</label> ' +
            '                           <div class="col-sm-3" style="margin-top: 15px">' +
            '                               <input id="jydd"  type="text" name="" required placeholder="请输入借用地点" class="form-control">' +
            '                           </div>' +
            '                            <label class="col-sm-2 control-label" style="margin-top: 15px">借用原因</label>\n' +
            '                            <div class="col-sm-4">\n' +
            '                                <input id="bzxx" type="text" name="" required placeholder="请输入借用原因"\n' +
            '                                       class="form-control" style="margin-top: 15px">\n' +
            '                            </div>\n' +
            '                        </div><br>\n' +
            '                        <div class="form-group" id="laydate">\n' +
            '                            <label class="col-sm-2 control-label">开始时间</label>\n' +
            '                            <div class="col-sm-3">\n' +
            '                                <input type="text" name="starttime" required placeholder="yyyy-MM-dd HH:mm:ss"\n' +
            '                                       class="form-control"\n' +
            '                                       id="test1">\n' +
            '                            </div>\n' +
            '                            <label class="col-sm-2 control-label">结束时间</label>\n' +
            '                            <div class="col-sm-4">\n' +
            '                                <input disabled="disabled" type="text" name="endtime" required placeholder="yyyy-MM-dd HH:mm:ss"\n' +
            '                                       class="form-control"\n' +
            '                                       id="test2">\n' +
            '                            </div>\n' +
            '                        </div>'
        $('.detailDiv').append(detail)
    }

    //获取时间
    function getNowTime(x) {
        var myDate = new Date();
        //获取当前年
        var year = myDate.getFullYear();
        //获取当前月
        var month = myDate.getMonth() + 1;
        //获取当前日
        var date = myDate.getDate();
        if (x == 1) {
            date = date + 3;
        }
        var h = myDate.getHours(); //获取当前小时数(0-23)
        var m = myDate.getMinutes(); //获取当前分钟数(0-59)
        var s = myDate.getSeconds();
        let now = year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);
        return now;
    }

    function p(s) {
        return s < 10 ? '0' + s : s;
    }

	<!--    拆分时间字符串-->
	function stringToTime(str) {
		var date = str;
		date = date.substring(0, 19);
		date = date.replace(/-/g, '/');
		date = date.replace(/:/g, '/');
		date = date.replace(/\s/g, "/");
		var a = date.split('/');
		return a;
	};

    //    初始化时间日期选择器
    function initialize() {
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            // laydate.render({
            //     elem: '#test1',
            //     type: 'datetime',
            //     min: getNowTime(),
            //     max: getNowTime(1),
            //     done: function (value, date, endDate) {
            //         $('#test2').val("");
            //         $('#test2').attr('disabled', false)
            //         if (value != '') {
            //             endTime.config.min = {
            //                 year: date.year,
            //                 month: date.month - 1,//关键
            //                 date: date.date,
            //                 hours: date.hours,
            //                 minutes: date.minutes,
            //                 seconds: date.seconds
            //             };
            //             endTime.config.max = {
            //                 year: date.year,
            //                 month: date.month - 1,//关键
            //                 date: date.date + 1,
            //                 hours: date.hours,
            //                 minutes: date.minutes,
            //                 seconds: date.seconds
            //             };
            //         } else {
            //             endTime.config.min = {
            //                 year: 2200,
            //                 month: 0,
            //                 date: 1,
            //             };
            //         }
            //         ;
            //     }
            // });


			var startTime = laydate.render({
				elem: '#test1',
				type: 'datetime',
				btns: ['confirm'],
				// min: 0,
				// max: 100,
			 	min: getNowTime(),
			 	max: getNowTime(1),
				done: function (value, date, endDate) {
					//把结束时间的最小值改为开始时间
					if(value != ''){
						endTime.config.min = {
							year: date.year,
							month: date.month - 1,//关键
							date: date.date,
							hours: date.hours,
							minutes: date.minutes,
							seconds: date.seconds
						};

						endTime.config.max = {
							 year: date.year,
							 month: date.month - 1,//关键
							 date: date.date + 1,
							 hours: date.hours,
							 minutes: date.minutes,
							 seconds: date.seconds
						 };
					}else{
						endTime.config.min = {
							year: 2200,
							month: 0,//关键
							date: 1,
							// hours: date.hours,
							// minutes: date.minutes,
							// seconds: date.seconds
						};
					};


					var id2 = parseInt($("option:selected").prop('id'));
					var starttime = value;
					let a=stringToTime(starttime);
					if(a[3]<8||a[3]>=22||(a[3]==21&&a[4]>=20)){
						$("#test1").val(123);
                        layer.alert("请注意借用物品在值班时间内：<br/>" +
                            "春秋冬：8:00~11:50   14:00~20:50 <br/>" +
                            "夏&nbsp;&nbsp;&nbsp;&nbsp;季：8:00~11:50   14:30~21:20 <br/>");
						console.log($("#test1").val())
						return
					}

					var endtime = $("input[name='endtime']").val();

					let b=stringToTime(endtime);
					if(b[3]<8||b[3]>=22||(b[3]==21&&b[4]>=20)){
						$("#test2").val('123')
                        layer.alert("请注意借用物品在值班时间内：<br/>" +
                            "春秋冬：8:00~11:50   14:00~20:50 <br/>" +
                            "夏&nbsp;&nbsp;&nbsp;&nbsp;季：8:00~11:50   14:30~21:20 <br/>");
						return
					}

					//8-21:20点
					if(date.hours<=7||date.hours>=22||(date.hours==21&&date.minutes>=20)){
						layer.alert("请注意借用物品在值班时间内：<br/>" +
                            "春秋冬：8:00~11:50   14:00~20:50 <br/>" +
                            "夏&nbsp;&nbsp;&nbsp;&nbsp;季：8:00~11:50   14:30~21:20 <br/>");
						$("input[name='starttime']").val('');
					};
					//监听huiyishijian
					if (id2 != "" && starttime != ""&&date.hours>=8&&date.hours<=22) {
						$("input[name='endtime']").removeAttr("disabled");

						//
						// $.ajax({
						// 	type: "POST",
						// 	url: "/user/judgeStartTime",
						// 	data: {
						// 		"mid": id2,
						// 		"starttime": starttime,
						// 	},
						// 	success: function (msg) {
						// 		if (msg != ("true")) {
						// 			// $.alert("温馨提示","时间冲突，请重新选择");
						// 			layer.alert('时间冲突，请重新选择');
						// 			$("input[name='starttime']").val("");
						// 			$("input[name='endtime']").val("");
						// 			$("input[name='endtime']").prop("disabled", true);
						// 		}
						// 		;   // if(msg!=true){form.render();};
						// 	},
						// 	error: function (nn) {
						// 		// $.alert("温馨提示","提交失败");
						// 		layer.alert('提交失败');
						// 	}
						// });


					} else {
						$("input[name='endtime']").prop("disabled", true);
					}
					;//if结束
				}//done结束
			});



            // var endTime = laydate.render({
            //     elem: '#test2',
            //     type: 'datetime',
            //     btns: ['now', 'confirm'],
            //     min: 0,
            //     max: 100
            // });

			var endTime = laydate.render({
				elem: '#test2',
				type: 'datetime',
				btns: ['now', 'confirm'],
				min: 0,
				max: 100,
				done: function (value, date, endDate) {
					//把开始时间的最大值改为结束时间的值
					if(value != ''){
						startTime.config.max = {
							year: date.year,
							month: date.month - 1,//关键
							date: date.date,
							hours: date.hours,
							minutes: date.minutes,
							seconds: date.seconds
						};
					}else{
						startTime.config.max = {
							year: 2200,
							month: 0, //关键
							date: 1
						}
					};

					var id2 = parseInt($("option:selected").prop('id'));
					var endtime = value;
					var starttime = $("input[name='starttime']").val();
					//
					if(date.hours<=7||date.hours>=22||(date.hours==21&&date.minutes>=20)){
                        layer.alert("请注意借用物品在值班时间内：<br/>" +
                            "春秋冬：8:00~11:50   14:00~20:50 <br/>" +
                            "夏&nbsp;&nbsp;&nbsp;&nbsp;季：8:00~11:50   14:30~21:20 <br/>");
						$("input[name='endtime']").val("");
					};
					if (id2 != "" && starttime != "" && endtime != ""&&date.hours>=7&&date.hours<=22) {
						// $.ajax({
						// 	type: "POST",
						// 	url: "/user/judgeTime",
						// 	data: {
						// 		"mid": id2,
						// 		"starttime": starttime,
						// 		"endtime": endtime,
						// 	},
						// 	success: function (msg) {
						// 		// form.render();
						// 		if (msg != ("true")) {
						// 			layer.alert('时间冲突，请重新选择');
						// 			$("input[name='endtime']").val("");
						// 			$("input[name='starttime']").val("");
						// 			startTime.config.max = {
						// 				year: date.year+1,
						// 				month: date.month + 1,//关键
						// 				date: date.date+30,
						// 				hours: date.hours+24,
						// 				minutes: date.minutes+60,
						// 				seconds: date.seconds+10
						// 			};
						// 		} ;
						// 	},
						// 	error: function (nn) {
						// 		layer.alert('提交失败');
						// 	}
						// });
					}
					;//if结束
				}//done
			});//test2
        })
    }

    //加一天
    function addDate(time) {
        var timestamp = Date.parse(new Date(time));
        timestamp = timestamp / 1000;
        timestamp += 86400;//加一天
        var newTime = new Date(timestamp * 1000).format('yyyy-MM-dd HH:mm:ss');
        return newTime;
    }

    //日期格式
    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    //    详细信息非空
    function notEmpty() {
        let msg = false;
        if (people == '' || college == '' || phone == '' || tip == '' || startTime == '' || endTime == '') {
        } else {

            msg = true
        }
        return msg
    }

</script>
</body>

</html>
